import React, { useState, useEffect, useRef, useLayoutEffect } from "react";

import { ActivityIndicator, StatusBar, StyleSheet, View } from "react-native";
import {
  TabView,
  TabBar,
  NavigationState,
  SceneRendererProps,
} from "react-native-tab-view";
import HomePipeView from "../../components/HomePipeView";
import apiService from "../../services/ApiServices";
import ModalController, {
  CustomModalRef,
} from "../../components/ModalController";
import SignupModal from "../../components/SignupModal";
import LoginModal from "../../components/LoginModal";
import { HomeScreenProps } from "../../types/NavigationTypes";
import HomeSearchBar from "../../components/HomeSearchBar";

export type TabModel = {
  key: string;
  title: string;
  subList: any;
};
const HomeScreen: React.FC<HomeScreenProps> = ({ navigation }) => {
  const [index, onIndexChange] = useState(0);
  const [tabItems, setTabItems] = useState<TabModel[]>([]);
  const customModalRef = useRef<CustomModalRef>(null);
  const [isLoading, setIsLoading] = useState(true);

  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: () => <HomeSearchBar />,
      headerTitleAlign: "left",
    });
  }, [navigation]);

  useEffect(() => {
    ModalController.setModalRef(customModalRef);
    const fetchData = async () => {
      const data = await fetchHomeTagList();
      data.forEach((item) => {
        if (item.subList.length > 0) {
          item.subList.unshift({ id: "all", tag: "全部", subList: [] });
        }
      });
      setTabItems(data);
    };
    fetchData();
  }, []);

  const fetchHomeTagList = async (): Promise<TabModel[]> => {
    try {
      const result = await apiService.getHomeTagList();
      return result?.data?.map((item: any) => ({
        key: item.id.toString(),
        title: item.tag || "",
        subList: item.subList || [],
      }));
    } catch (error) {
      console.error("Error fetching home tag list", error);
      return [];
    } finally {
      setIsLoading(false);
    }
  };

  const renderTabBar = (
    props: SceneRendererProps & { navigationState: NavigationState<TabModel> }
  ) => (
    <TabBar
      {...props}
      scrollEnabled
      indicatorStyle={styles.indicator}
      style={styles.tabbar}
      labelStyle={styles.label}
      tabStyle={tabItems.length > 0 ? styles.tabStyle : styles.emptyTabStyle}
      activeColor="#3BC859"
      pressColor="rgba(255, 255, 255, 0)"
      pressOpacity={1}
    />
  );

  const renderScene = ({ route }: any) => {
    return <HomePipeView route={route} />;
  };

  return (
    <>
      <StatusBar barStyle="dark-content" backgroundColor="white" />
      {isLoading ? (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        >
          <ActivityIndicator size="large" color="#3BC859" />
        </View>
      ) : (
        <TabView
          navigationState={{
            index,
            routes: tabItems,
          }}
          lazy={true}
          renderScene={renderScene}
          renderTabBar={renderTabBar}
          onIndexChange={onIndexChange}
        />
      )}

      <LoginModal ref={customModalRef} />
      {/* <SignupModal ref={customModalRef}/> */}
    </>
  );
};

export default HomeScreen;

const styles = StyleSheet.create({
  tabbar: {
    backgroundColor: "white",
    elevation: 0,
    borderBottomWidth: 0.5,
    borderBottomColor: "rgba(0,0,0,0.05)",
  },
  indicator: {
    backgroundColor: "#3BC859",
    height: 2,
  },
  label: {
    fontWeight: "400",
    color: "grey",
    fontSize: 15,
  },
  tabStyle: {
    width: "auto",
    marginVertical: -3,
  },
  emptyTabStyle: {
    width: "100%",
  },
});
